package com.jarveis.frame.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.apache.log4j.Logger;

import com.jarveis.frame.lang.CharacterUtil;
import com.jarveis.frame.security.MD5Cipher;

import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

/**
 * freemarker工具类
 * 
 * @author liuguojun
 */
public class FreemarkerUtil {

	private static final Logger logger = Logger.getLogger(FreemarkerUtil.class);

	private static Map<String, freemarker.template.Configuration> configMap = new HashMap();

	/**
	 * 获取模板配置
	 * 
	 * @param tempBase
	 * @return
	 */
	private static freemarker.template.Configuration getConfig(String tempBase) {
		String key = MD5Cipher.encrypt(tempBase);
		freemarker.template.Configuration config = (freemarker.template.Configuration) configMap
				.get(key);
		if (config == null) {
			try {
				config = new freemarker.template.Configuration();

				config.setDirectoryForTemplateLoading(new File(tempBase));
				config.setEncoding(Locale.CHINA, CharacterUtil.UTF8);

				config.setObjectWrapper(new DefaultObjectWrapper());

				config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);

				configMap.put(key, config);
			} catch (IOException ex) {
				logger.error(ex.getMessage(), ex);
			}
		}

		return config;
	}

	/**
	 * 生成静态文件
	 * 
	 * @param tempBase
	 * @param templatePath
	 * @param htmlPath
	 * @param params
	 */
	public static void createHtml(String tempBase, String templatePath,
			String htmlPath, Map params) {
		try {
			String dirPath = htmlPath.substring(0, htmlPath.lastIndexOf("/"));
			File dirFile = new File(dirPath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}

			Template template = getConfig(tempBase).getTemplate(templatePath);
			FileOutputStream fos = new FileOutputStream(htmlPath);
			OutputStreamWriter osw = new OutputStreamWriter(fos, CharacterUtil.UTF8);
			BufferedWriter sw = new BufferedWriter(osw);

			template.process(params, sw);
			sw.flush();
			sw.close();
			fos.close();

			logger.info("generate html success ---> " + htmlPath);
		} catch (Exception ex) {
			logger.error("generate html error! " + htmlPath, ex);
		}
	}
}
